<template>
    <el-card class="card">
        <el-form :inline="true">
            <el-form-item label="角色名：">
                <el-input v-model="roleName" placeholder="请输入搜索的角色名" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getRoleData()">搜索</el-button>
                <el-button type="primary" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card style="margin-top: 20px;">
        <el-row>
            <el-col>
                <el-button icon="Plus" type="primary" @click="addRole">添加职位</el-button>
            </el-col>
        </el-row>
        <el-table border style="margin: 10px 0px;" :data="allRole">
            <el-table-column type="index" align="center" label="#"></el-table-column>
            <el-table-column label="ID" align="center" prop="id"></el-table-column>
            <el-table-column label="职位名称" align="center" prop="roleName" show-overflow-tooltip></el-table-column>
            <el-table-column label="创建世间" align="center" show-overflow-tooltip prop="createTime"></el-table-column>
            <el-table-column label="更新时间" align="center" show-overflow-tooltip prop="updateTime"></el-table-column>
            <el-table-column label="操作" width="280px" align="center">
                <!-- row:已有的职位对象 -->
                <template #="{ row }">
                    <el-button type="primary" size="small" icon="User" @click="setPermisstion(row.id)">分配权限</el-button>
                    <el-button type="primary" size="small" icon="Edit" @click="updateRole(row)">编辑</el-button>
                    <el-popconfirm :title="`确定要要删除${row.roleName}吗?`" @confirm="deleRole(row.id)">
                        <template #reference>
                            <el-button type="primary" size="small" icon="Delete">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[5, 7, 9]" :background="true"
            layout=" prev, pager, next, jumper,->, sizes,total" :total="total" @size-change="getRoleData()"
            @current-change="getRoleData" />
    </el-card>
    <el-dialog v-model="roleDialogVisible" width="30%" @close="handleClose">
        <template #header>
            {{ roleInfo.id ? "编辑角色" : "新增角色" }}
        </template>
        <el-form :model="roleInfo" ref="roleRef" :rules="roleRules" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户姓名" prop="roleName">
                <el-input v-model="roleInfo.roleName" placeholder="请输入角色名称" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="addTrueRole">
                    保存
                </el-button>
            </span>
        </template>
    </el-dialog>
    <el-drawer v-model="QxDrawer">
        <template #header>
            <h4>分配权限</h4>
        </template>
        <template #default>
            <el-tree ref="tree" :default-checked-keys="nodeKeys" :data="qxList" show-checkbox node-key="id"
                default-expand-all :props="defaultProps" />
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="QxDrawer = false">取消</el-button>
                <el-button type="primary" @click="qxTrue">
                    确定
                </el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script setup lang="ts">
import { getRole, addOrUpdateRole, removeRole, toAssign, doAssign } from '@/api/art/role'
import { onMounted, ref, reactive } from 'vue'
import settingState from '@/store/modules/setting';
import type { Role, Qx } from '@/api/art/role/type';
import { ElMessage } from 'element-plus';
const setState = settingState()
// 角色数据表
const allRole = ref<Role[]>([])
// 权限
const qxList = ref<Qx[]>([])
// 搜索角色参数
const roleName = ref<string>('')

const pageNo = ref<number>(1)
const pageSize = ref<number>(5)
const total = ref<number>(0)
// 新增角色请求参数
const roleInfo = reactive<Role>({
    roleName: ''
})
// 配置权限树节点
const defaultProps = reactive({
    children: 'children',
    label: 'name',
})
// 树节点
const tree = ref()

// 表单实例
const roleRef = ref()
// 新增编辑角色
const roleDialogVisible = ref<boolean>(false)
// 分配权限
const QxDrawer = ref<boolean>(false)
// 已有权限
const nodeKeys = ref<number[]>([])
// 初始钩子
const validateRoleName = (rule: any, value: any, callback: any) => {
    if (value.trim().length >= 5) {
        callback()
    } else {
        callback(new Error("角色名至少5位"))
    }
}
// 表单验证规则
const roleRules = {
    roleName: [
        { required: true, trigger: 'blur', validator: validateRoleName },
    ]
}

onMounted(() => {
    getRoleData()
})
// 获取角色
const getRoleData = async (page: number = 1) => {
    pageNo.value = page
    const data = await getRole(pageNo.value, pageSize.value, roleName.value)
    if (data.code == 200) {
        allRole.value = data.data.records
        total.value = data.data.total
    }
}
// 关闭角色弹窗
const handleClose = () => {
    roleDialogVisible.value = false
    roleRef.value.resetFields()
}
// 重置
const reset = () => {
    setState.mainFlag = !setState.mainFlag
}
// 添加角色
const addRole = () => {
    roleInfo.id = 0
    roleDialogVisible.value = true
}
// 确定新增
const addTrueRole = () => {
    roleRef.value.validate(async (valid: any) => {
        if (!valid) return
        const data = await addOrUpdateRole(roleInfo)
        if (data.code == 200) {
            ElMessage.success(roleInfo.id ? "编辑角色成功" : "新增角色成功")
            getRoleData(pageNo.value)
        } else {
            ElMessage.error(roleInfo.id ? "编辑角色失败" : "新增角色失败")
        }
        roleDialogVisible.value = false
    })
}
// 分配权限
const setPermisstion = async (roleId: number) => {
    roleInfo.id = roleId
    const data = await toAssign(roleId)
    if (data.code === 200) {
        qxList.value = data.data
        nodeKeys.value = setQx(qxList.value, [])
    }
    QxDrawer.value = true
}
// 设置权限
const setQx = (qxList: Qx[], arr: number[]) => {
    qxList.forEach(item => {
        if (item.select && item.level == 4) {
            arr.push(item.id)
        }
        if (item.children && item.children.length >= 1) {
            setQx(item.children, arr)
        }
    })
    return arr
}
const qxTrue = async () => {
    let arr = tree.value.getHalfCheckedKeys()
    let arr1 = tree.value.getCheckedKeys()
    let selectArr = arr.concat(arr1)
    const data = await doAssign((roleInfo.id as number), selectArr)
    if (data.code == 200) {
        QxDrawer.value = false
        ElMessage.success('权限设置成功')
        window.location.reload()
    } else {
        ElMessage.success('权限设置失败')

    }
}
// 确定要要删除 
const deleRole = async (roleId: number) => {
    const data = await removeRole(roleId)
    if (data.code == 200) {
        ElMessage.success("删除次角色成功")
        getRoleData(allRole.value.length > 1 ? pageNo.value : pageNo.value - 1)
    } else {
        ElMessage.success("删除次角色失败")
    }
}
// 角色编辑
const updateRole = (row: Role) => {
    Object.assign(roleInfo, row)
    roleDialogVisible.value = true
}
</script>
<script lang="ts">
export default {
    name: 'Role'
}
</script>
<style scoped lang="scss">
.card {
    height: 80px;

    .el-form {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}
</style>